package com.braveman.im.ui.activity;

import android.Manifest;
import android.app.ActivityManager;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.braveman.im.R;
import com.braveman.im.application.AppApplication;
import com.braveman.im.bean.PersonalDataBaen;
import com.braveman.im.constant.Constants;
import com.braveman.im.manager.ApiManager;
import com.braveman.im.service.GetuiService;
import com.braveman.im.service.PushService;
import com.braveman.im.ui.activity.message.LoginActivity;
import com.braveman.im.utils.AppUtils;
import com.braveman.im.utils.PermissionUtils;
import com.ht.baselibs.retrofit.NetCallBack;
import com.ht.baselibs.ui.base.BaseActivity;
import com.ht.baselibs.utils.ActivityUtils;
import com.ht.baselibs.utils.ChannelUtils;
import com.ht.baselibs.utils.LogUtils;
import com.ht.baselibs.utils.SharedPreferencesUtils;
import com.igexin.sdk.PushManager;
import com.umeng.analytics.MobclickAgent;
import com.vondear.rxtools.RxBarTool;

import java.util.ArrayList;
import java.util.List;

import cn.magicwindow.MLinkAPIFactory;
import cn.magicwindow.mlink.annotation.MLinkRouter;
import retrofit2.Call;
import retrofit2.Response;

@MLinkRouter(keys = "one")
public class SplashActivity extends BaseActivity {

    public static final int MSG_WHAT_LAUNCHER_TIME_UP = 0;
    private static final int REQUEST_PERMISSION_SD_CAED_CODE = 1;
    private Thread thread;
    //启动图片集合
    private static final Integer[] DEFAULT_PIC_URLS = {R.mipmap.guide_01, R.mipmap.guide_01, R.mipmap.guide_01, R.mipmap.guide_01};
    private ViewPager viewPager;
    private PagerAdapter adapter;
    private List<View> viewPages = new ArrayList<>();
    //包裹点点的LinearLayout
    private ViewGroup group;
    private ImageView imageView;
    //定义一个ImageVIew数组，来存放生成的小园点
    private ImageView[] imageViews;
    private TextView mTvGoUse;

    @Override
    protected boolean isStaticPage() {
        return true;
    }

    @Override
    protected boolean isFulleScreen() {
        return true;
    }

    @Override
    protected void initChannel() {
        MobclickAgent.startWithConfigure(new MobclickAgent.UMAnalyticsConfig(this, "586c9a9e6e27a428320011de", ChannelUtils.getChannel()));
    }

    @Override
    protected void initTitleBar() {

    }

    @Override
    protected int initContentView() {
        return R.layout.activity_splash;
    }

    @Override
    protected void initChildView() {

        viewPager = (ViewPager) findViewById(R.id.viewPager);
        group = (ViewGroup) findViewById(R.id.viewGroup);
        mTvGoUse = (TextView) findViewById(R.id.tv_go_use);
        initPageAdapter();
        initPointer();
        initEvent();
        MLinkAPIFactory.createAPI(this).registerWithAnnotation(this);


        try {// TODO: 2017/6/29 友盟bug出现率比较高
            PushManager.getInstance().initialize(this.getApplicationContext(), PushService.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        PushManager.getInstance().registerPushIntentService(this.getApplicationContext(), GetuiService.class);
        Boolean isServiceRunningPush = false;
        //检查Service状态
        ActivityManager manager = (ActivityManager) AppApplication.getContext().getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if ("com.jinkaimen.addwallet.service.PushService".equals(service.service.getClassName())) {
                isServiceRunningPush = true;
            }
        }
        if (!isServiceRunningPush) {
            Intent i = new Intent(this, PushService.class);
            this.startService(i);
        }
    }

    @Override
    protected void initChildData() {
        boolean hasWriteSDCardPermission = PermissionUtils.hasWriteSDCardPermission();

        if (!hasWriteSDCardPermission) {


            showPopupWindow();
            return;
        } else {
            thread = new Thread(new Runnable() {
                public void run() {
                    try {
                        Thread.sleep(2000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    Message msg = new Message();
                    msg.what = MSG_WHAT_LAUNCHER_TIME_UP;
                    mHandler.sendMessage(msg);
                }
            });
            thread.start();
        }



    }

    @Override
    protected void setChildViewListener() {
        mTvGoUse.setOnClickListener(this);
    }

    @Override
    protected void handleMessage(BaseActivity context, Message msg) {
        switch (msg.what) {
            case MSG_WHAT_LAUNCHER_TIME_UP:
//                if (SharedPreferencesUtils.getBool(IS_FIRST_OPEN, true)){
//                    ActivityUtils.startActivityAndFinishByAlpha(this, GuideActivity.class);
//                } else {
//                    ActivityUtils.startActivityAndFinish(this, HomeActivity.class);
//                }
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);


        if (requestCode == REQUEST_PERMISSION_SD_CAED_CODE) {
            if (grantResults.length > 1
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {

                //        这里做2秒的延时操作
                thread = new Thread(new Runnable() {
                    public void run() {
                        try {
                            Thread.sleep(2000);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        Message msg = new Message();
                        msg.what = MSG_WHAT_LAUNCHER_TIME_UP;
                        mHandler.sendMessage(msg);
                    }
                });
                thread.start();

            } else {
                ActivityUtils.finishActivityByAlpha(this);
            }
        } else {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }


    private void showPopupWindow() {

        final Dialog updateDialog = new Dialog(this, R.style.updateDialog);
        View view = View.inflate(this, R.layout.dialog_splash_per,
                null);

        Window window = updateDialog.getWindow();
        WindowManager m = getWindowManager();
        Display d = m.getDefaultDisplay(); // 获取屏幕宽、高用
        WindowManager.LayoutParams p = window.getAttributes(); // 获取对话框当前的参数值
        p.height = (int) (d.getHeight() * 0.6); // 改变的是dialog框在屏幕中的位置而不是大小
        p.width = (int) (d.getWidth() * 0.65); // 宽度设置为屏幕的0.65
        window.setAttributes(p);
        updateDialog.setContentView(view);
        updateDialog.setCancelable(false);

        updateDialog.show();
        view.findViewById(R.id.btn_splash_act_dialog_next).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateDialog.dismiss();
                ActivityCompat.requestPermissions(SplashActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_PERMISSION_SD_CAED_CODE);
            }
        });
    }

    //初始化ViewPager
    private void initPageAdapter() {
/**
 * 对于这几个想要动态载入的page页面，使用LayoutInflater.inflate()来找到其布局文件，并实例化为View对象
 */
        LayoutInflater inflater = LayoutInflater.from(this);
        View page1 = inflater.inflate(R.layout.view_page_splash1, null);
        View page2 = inflater.inflate(R.layout.view_page_splash1, null);
        View page3 = inflater.inflate(R.layout.view_page_splash1, null);
        //添加到集合中
        viewPages.add(page1);
        viewPages.add(page2);
        viewPages.add(page3);
        adapter = new PagerAdapter() {
            //获取当前界面个数
            @Override
            public int getCount() {
                return viewPages.size();
            }

            //判断是否由对象生成页面
            @Override
            public boolean isViewFromObject(View view, Object object) {
                return view == object;
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                container.removeView(viewPages.get(position));
            }

            //返回一个对象，这个对象表明了PagerAdapter适配器选择哪个对象放在当前的ViewPager中
            @Override
            public Object instantiateItem(ViewGroup container, int position) {
                View view = viewPages.get(position);
                container.addView(view);
                return view;
            }
        };
    }

    //初始化下面的小圆点的方法
    private void initPointer() {
        //有多少个界面就new多长的数组
        imageViews = new ImageView[viewPages.size()];
        for (int i = 0; i < imageViews.length; i++) {
            imageView = new ImageView(this);
            //设置控件的宽高
            //设置控件的padding属性
            imageView.setPadding(20, 0, 20, 0);
            imageViews[i] = imageView;
            //初始化第一个page页面的图片的原点为选中状态
            if (i == 0) {
                //表示当前图片
                imageViews[i].setBackgroundResource(R.mipmap.red_hint_icon);
                /**
                 * 在java代码中动态生成ImageView的时候
                 * 要设置其BackgroundResource属性才有效
                 * 设置ImageResource属性无效
                 */
            } else {
                imageViews[i].setBackgroundResource(R.mipmap.cb_normal);
            }
            group.addView(imageViews[i]);
        }
    }

    //为控件绑定事件,绑定适配器
    private void initEvent() {
        viewPager.setAdapter(adapter);
        viewPager.addOnPageChangeListener(new GuidePageChangeListener());
    }

    //ViewPager的onPageChangeListener监听事件，当ViewPager的page页发生变化的时候调用
    public class GuidePageChangeListener implements ViewPager.OnPageChangeListener {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        //页面滑动完成后执行
        @Override
        public void onPageSelected(int position) {
            //判断当前是在那个page，就把对应下标的ImageView原点设置为选中状态的图片
            for (int i = 0; i < imageViews.length; i++) {
                imageViews[position].setBackgroundResource(R.mipmap.red_hint_icon);
                if (position != i) {
                    imageViews[i].setBackgroundResource(R.mipmap.cb_normal);
                }
            }
            mTvGoUse.setVisibility(position == 2 ? View.VISIBLE : View.GONE);
        }

        //监听页面的状态，0--静止  1--滑动   2--滑动完成
        @Override
        public void onPageScrollStateChanged(int state) {
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_go_use:
                ActivityUtils.startActivityAndFinish(SplashActivity.this, !AppUtils.isLogin() ? LoginActivity.class : HomeActivity.class);
                break;
        }
    }

}
